package cuongnh.project.japanesediary.vocabulary.ui.view;

import java.util.Collections;
import java.util.List;

import org.eclipse.core.databinding.observable.ChangeEvent;
import org.eclipse.core.databinding.observable.IChangeListener;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import cuongnh.coreframework.ui.workbench.common.view.AutoUpdateView;
import cuongnh.project.japanesediary.vocabulary.common.CommonUtils;
import cuongnh.project.japanesediary.vocabulary.dao.VocabularyDao;
import cuongnh.project.japanesediary.vocabulary.model.Vocabulary;
import cuongnh.project.japanesediary.vocabulary.ui.common.composite.SearchComposite;
import de.ralfebert.rcputils.concurrent.UIProcess;
import de.ralfebert.rcputils.tables.TableViewerBuilder;

@Component("vocabularyListView")
@Scope("prototype")
public class VocabularyListView extends AutoUpdateView {

	public static final String ID = "cuongnh.project.japanesediary.vocabulary.ui.view.VocabularyListView"; //$NON-NLS-1$
	private final FormToolkit toolkit = new FormToolkit(Display.getCurrent());

	private TableViewerBuilder vocabularyList;

	private SearchComposite search;

	@Autowired
	private VocabularyDao vocabularyDao;

	public VocabularyListView() {
	}

	/**
	 * Job which loads the list of addresses and schedules an UIJob to refresh
	 * the UI afterwards.
	 */
	public class LoadVocabularyListJob extends UIProcess {

		private List<Vocabulary> vocabularies;

		public LoadVocabularyListJob(Display display) {
			super(display, "Load vocabulary list");
		}

		@Override
		protected void runInBackground(IProgressMonitor monitor) {
			vocabularies = (vocabularyDao != null) ? vocabularyDao.getAll()
					: Collections.<Vocabulary> emptyList();
		}

		@Override
		protected void runInUIThread() {
			if (vocabularyList != null
					&& !vocabularyList.getTable().isDisposed()) {
				vocabularyList.setInput(vocabularies);
				vocabularyList.getTable().getParent().layout();
				vocabularyList.getTableViewer().refresh();
			}
		}
	}

	/**
	 * Create contents of the view part.
	 * 
	 * @param parent
	 */
	@Override
	public void createPartControl(Composite parent) {
		createActions();
		initializeToolBar();
		initializeMenu();

		// Search control
		search = new SearchComposite(parent);

		// Separate composite to embed the table
		Composite tableComposite = new Composite(parent, SWT.NONE);

		vocabularyList = new TableViewerBuilder(tableComposite);
		vocabularyList.createColumn("Vocabulary").bindToProperty("vocabulary")
				.setPercentWidth(30).build();
		vocabularyList.createColumn("Meaning").bindToProperty("vnMeaning")
				.setPercentWidth(70).build();
		// change the height of the row
		// CommonUtils.changeTableRowHeigh(vocabularyList.getTable());
		// Filter
		vocabularyList.getTableViewer().addFilter(new ViewerFilter() {

			@Override
			public boolean select(Viewer viewer, Object parentElement,
					Object element) {
				Vocabulary vocabulary = (Vocabulary) element;
				String text = String.valueOf(search.observeText().getValue());
				if (vocabulary.getVocabulary().toLowerCase()
						.contains(text.toLowerCase())
						|| vocabulary.getFurigana().toLowerCase()
								.contains(text.toLowerCase())) {
					return true;
				}

				return false;
			}

		});
		search.observeText().addChangeListener(new IChangeListener() {

			@Override
			public void handleChange(ChangeEvent event) {
				refresh();
				vocabularyList.getTableViewer().refresh();
			}

		});

		// ContextMenu contextMenu = new ContextMenu(
		// vocabularyList.getTableViewer(), getSite());
		// contextMenu.setDefaultItemHandling(true);

		// Layout
		GridLayoutFactory.fillDefaults().numColumns(1).applyTo(parent);
		GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER)
				.applyTo(search);
		GridDataFactory.fillDefaults().grab(true, true).applyTo(tableComposite);

		refresh();
		getSite().setSelectionProvider(vocabularyList.getTableViewer());
		CommonUtils.vocabulariesHookDoubleClickCommand(vocabularyList
				.getTableViewer());
		this.setInterval(1);
		this.startAutoReload();
	}

	public void dispose() {
		toolkit.dispose();
		super.dispose();
	}

	/**
	 * Create the actions.
	 */
	private void createActions() {
		// Create the actions
	}

	/**
	 * Initialize the toolbar.
	 */
	private void initializeToolBar() {
		IToolBarManager toolbar = getViewSite().getActionBars()
				.getToolBarManager();
	}

	/**
	 * Initialize the menu.
	 */
	private void initializeMenu() {
		IMenuManager manager = getViewSite().getActionBars().getMenuManager();
		manager.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {

			}
		});
	}

	@Override
	public void setFocus() {
		vocabularyList.getTable().setFocus();
	}

	public void refresh() {
		if (vocabularyList != null && !vocabularyList.getTable().isDisposed()) {
			new LoadVocabularyListJob(vocabularyList.getTable().getDisplay())
					.schedule();
		}
	}

	@Override
	public void update() {
		refresh();
	}

}
